package com.kevin.j2eeToolBox.spring;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
 * 模拟spring如何生成bean
 * 
 * @author wyzh
 *
 */
public class ClassPathXMLApplication {

	private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
	private Map<String, Object> sigletons = new HashMap<String, Object>();

	public ClassPathXMLApplication(String fileName) {
		this.parseXMl(fileName);
		this.createBeanInstance();
	}

	private void parseXMl(String fileName) {

		File file = new File(fileName);
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(file);

			Element element = document.getRootElement();
			element.elementIterator();
			for (Iterator iterator = element.elementIterator(); iterator
					.hasNext();) {
				Element bean = (Element) iterator.next();
				String id = bean.attributeValue("id");
				String clazz = bean.attributeValue("class");

				BeanDefinition beanDefine = new BeanDefinition(id, clazz);
				beanDefines.add(beanDefine);
			}

		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void createBeanInstance() {

		for (BeanDefinition beanDefinition : beanDefines) {
			try {
				if (beanDefinition.getClassName() != null
						&& !"".equals(beanDefinition.getClassName().trim()))
					sigletons.put(beanDefinition.getId(),
							Class.forName(beanDefinition.getClassName())
									.newInstance());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public Object getBean(String beanName) {

		return this.sigletons.get(beanName);
	}
}
